import java.util.Date;
import java.util.TimerTask;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class Task2 extends TimerTask {

  @SuppressWarnings("deprecation")
  @Override
  public void run() {
    System.out.println("----task2 start--------" + new Date().toLocaleString());
    try {
      Thread.sleep(5000);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    System.out.println("----5s later, task2 end--------" + new Date().toLocaleString());
  }

  static class Task1 extends TimerTask {

    @SuppressWarnings("deprecation")
    @Override
    public void run() {
      System.out.println("----task1 start--------" + new Date().toLocaleString());
      try {
        Thread.sleep(3000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      System.out.println("----3s later, task1 end--------" + new Date().toLocaleString());
    }
  }

  public static void main(String[] args) {

    ScheduledExecutorService pool = Executors.newScheduledThreadPool(2);//启用2个线程

    Task1 t1 = new Task1();
    // 马上运行，任务消耗3秒。运行结束后等待2秒。【有空余线程时】，再次运行该任务
    pool.scheduleWithFixedDelay(t1, 0, 2, TimeUnit.SECONDS);

    // 马上运行，任务消耗5秒，运行结束后等待2秒。【有空余线程时】，再次运行该任务
    Task2 t2 = new Task2();
    pool.scheduleWithFixedDelay(t2, 0, 2, TimeUnit.SECONDS);

  }



}
